#include "tx_api.h"
#include "nx_api.h"
#include "nx_bsd.h"

#include "debug.h"

#define APP_UDP_CLIENT_STACK 512

#define SERVER_PORT 50000

TX_THREAD thread_udp_client;

static void app_udp_client(ULONG thread_input);

void app_udp_client_create(TX_BYTE_POOL *pool)
{
	char *pointer = TX_NULL;
	
	tx_byte_allocate(pool,(void **)&pointer,APP_UDP_CLIENT_STACK,TX_NO_WAIT);
	if(!pointer)
	{
		PRINTF("%s failed..\r\n",app_udp_client_create);
		return ;
	}
	
	tx_thread_create(&thread_udp_client,"udp client",app_udp_client,0,pointer,APP_UDP_CLIENT_STACK,3,3,TX_NO_TIME_SLICE,TX_AUTO_START);
}

static void app_udp_client(ULONG thread_input)
{
	int status;
	int sockfd;
	int addrlen;
	struct sockaddr_in serveraddr;
	struct sockaddr_in peeraddr;
	char recv_buf[64];
	char send_buf[] = {"hello server..\r\n"};
	
	sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
	if(sockfd == ERROR)
	{
		PRINTF("socket failed..\r\n");
		return ;
	}
	
	memset(&serveraddr,0,sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_addr.s_addr = htonl(IP_ADDRESS(192,168,0,152));
	serveraddr.sin_port = htons(SERVER_PORT);
	
	for(;;)
	{
		status = sendto(sockfd,send_buf,sizeof(send_buf),0,(struct sockaddr *)&serveraddr,sizeof(serveraddr));
		if(status == ERROR)
		{
			PRINTF("sendto failed..\r\n");
			continue ;
		}
		
		memset(recv_buf,0,sizeof(recv_buf));
		addrlen = sizeof(struct sockaddr_in);
		status = recvfrom(sockfd,recv_buf,sizeof(recv_buf),0,(struct sockaddr *)&peeraddr,&addrlen);
		if(status == ERROR)
		{
			PRINTF("recvfrom failed..\r\n");
		}
		else
		{
			PRINTF("recv:%s\r\n",recv_buf);
		}
		
		tx_thread_sleep(NX_IP_PERIODIC_RATE);
	}
	
	soc_close(sockfd);
}
